package tracex

import (
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/sdk/resource"
	tracesdk "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.9.0"
)

// SetJaegerServerTracer 设置应用服务的追踪器
func SetJaegerServerTracer(name string, env string, url string) error {
	exp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
	if err != nil {
		return err
	}

	res, err := resource.Merge(
		resource.Default(),
		resource.NewSchemaless(
			semconv.ServiceNameKey.String(name+"-"+env),
			semconv.DeploymentEnvironmentKey.String(env),
		))
	if err != nil {
		return err
	}

	tp := tracesdk.NewTracerProvider(
		// 将采样率设置为 ratio = 1.0
		tracesdk.WithSampler(tracesdk.TraceIDRatioBased(1.0)),
		tracesdk.WithBatcher(exp),
		tracesdk.WithResource(res),
	)
	otel.SetTracerProvider(tp)

	return nil
}
